<template>
  <div class="main sign-in-rule-edit">
    <section>
      <el-form :model="formData" size="medium" ref="form" label-width="100px">
        <el-form-item label="活动时间:" prop="activityTimeRange" :rules="commonRules.notNullRule">
          <el-date-picker
            style="width: 500px"
            v-model="formData.activityTimeRange"
            type="datetimerange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="timestamp"
            :disabled="!isEdit">
          </el-date-picker>
          <div style="line-height: 1;padding-top: 8px;">
            当前活动周期：{{formatDate(dateData.currentRuleStartDate)}} - {{formatDate(dateData.currentRuleEndDate)}} <span style="padding-left: 24px"></span>
            最近活动周期：{{formatDate(dateData.nextRuleStartDate)}} - {{formatDate(dateData.nextRuleEndDate)}}
          </div>
        </el-form-item>
        <el-form-item label="签到周期:">
          <div class="form-static">固定周期 7 天 <span>单个周期内，每个连签奖励只可被领取一次</span></div>
        </el-form-item>
        <el-form-item label="签到奖励:" prop="activitySignInRuleRewardMapList" :rules="commonRules.notNullRule">
          <div>
            <el-button v-if="isEdit" type="success" size="small" icon="el-icon-circle-plus" plain @click="showAdd" style="margin-bottom: 12px;">新建连签奖励</el-button>
            <el-table :data="formData.activitySignInRuleRewardMapList" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
              <el-table-column align="center" label="连签天数(天)" prop="signInDay" min-width="100"></el-table-column>
              <el-table-column align="center" label="连签奖励" min-width="100">
                <template slot-scope="scope">
                  <span v-if="scope.row.activitySignInRewardList.filter(i => i.rewardType===4).length"> 优惠券 </span>
                  <span v-if="scope.row.activitySignInRewardList.filter(i => i.rewardType===2).length"> 赠品 </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="奖励条件" prop="conditionType" min-width="100">
                <template slot-scope="scope">
                  <span v-if="scope.row.conditionType == 0">不限</span>
                  <span v-if="scope.row.conditionType == 2">普通/VIP</span>
                  <span v-if="scope.row.conditionType == 4">钻石/董事</span>
                  <!-- {{['不限', '', '未购买38礼包 或 29.9礼包', '', '已购买38礼包 或 29.9礼包'][scope.row.conditionType]}} -->
                </template>
              </el-table-column>
              <el-table-column align="center" label="是否首签" prop="useCycleIndex" min-width="100">
                <template slot-scope="scope">
                  {{scope.row.useCycleIndex ? '是' : '否'}}
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="100">
                <template slot-scope="scope">
                  <el-button type="text" @click="showEdit(scope.row, scope.$index)">{{isEdit ? '编辑' : '查看'}}</el-button>
                  <el-button type="text" @click="delItem(scope.$index)" :disabled="!isEdit">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

      </el-form>
      <div class="footer-btn">
        <el-button type="primary" v-if="isEdit" :loading="btnLoading" plain @click="save">保 存</el-button>
        <el-button type="default" plain @click="$router.push({ name: 'signIn' })">返 回</el-button>
      </div>

      <el-dialog title="设置连签奖励" :visible.sync="dialogFormVisible">
        <el-form :model="rewardData" ref="dialogForm" label-width="100px">
          <el-form-item label="连签天数：" prop="signInDay" :rules="commonRules.daysCheck">
            <el-input v-model="rewardData.signInDay" :disabled="!isEdit"></el-input>
          </el-form-item>
          <el-form-item label="奖励条件：">
            <el-select v-model="rewardData.conditionType" :disabled="!isEdit">
              <el-option label="不限" :value="0"></el-option>
              <el-option label="普通/VIP" :value="2"></el-option>
              <el-option label="钻石/董事" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否首签：">
            <el-radio v-model="rewardData.useCycleIndex" :label="1" :disabled="!isEdit">是</el-radio>
            <el-radio v-model="rewardData.useCycleIndex" :label="0" :disabled="!isEdit">否</el-radio>
          </el-form-item>
          <el-form-item label="奖励类型：">
            <el-radio v-model="rewardData.rewardType" :label="2" :disabled="!isEdit">全部领取</el-radio>
            <el-radio v-model="rewardData.rewardType" :label="4" :disabled="!isEdit">M选N领取</el-radio>
          </el-form-item>
          <el-form-item label="最大可选：" v-if="rewardData.rewardType === 4" prop="nnum" :rules="commonRules.numberRule">
            <el-input v-model="rewardData.nnum" :disabled="!isEdit"></el-input>
          </el-form-item>
          <el-form-item label="优惠券：">
            <div>
              <el-button v-if="isEdit" type="primary" size="small" icon="el-icon-circle-plus" plain @click="jumpChoose('coupon')" style="margin-bottom: 12px;">添加优惠券</el-button>
              <el-table :data="rewardData.activitySignInRewardList.filter(i => i.rewardType === 4)" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column align="center" label="优惠券名称" prop="name" min-width="100"></el-table-column>
                <el-table-column align="center" label="优惠额度" prop="ext1" min-width="100">
                  <template slot-scope="scope">
                    {{scope.row.ext1}}元
                  </template>
                </el-table-column>
                <el-table-column align="center" label="使用门槛" prop="ext2" min-width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.ext2==='LIMITED'">满{{scope.row.ext3}}元</span>
                    <span v-else>无门槛</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button type="text" @click="delRewardItem(scope.row.sourceId)" :disabled="!isEdit">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <el-form-item label="赠品：">
            <div>
              <el-button v-if="isEdit" type="primary" size="small" icon="el-icon-circle-plus" plain @click="jumpChoose('goods')" style="margin-bottom: 12px;">添加商品</el-button>
              <el-button v-if="isEdit" type="primary" size="small" icon="el-icon-circle-plus" plain @click="jumpChoose('package')" style="margin-bottom: 12px;">添加套餐</el-button>
              <el-table :data="rewardData.activitySignInRewardList.filter(i => i.rewardType === 2)" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column align="center" label="赠品" prop="name" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="赠品数" width="80">
                  <template slot-scope="scope" v-if="scope.row.name">1件</template>
                </el-table-column>
                <el-table-column align="center" label="有效期（天）" min-width="60">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.validDays" placeholder="请输入" :disabled="!isEdit"></el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="运费（元）" min-width="60">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.freight" placeholder="填0包邮" :disabled="!isEdit"></el-input>
                  </template>
                </el-table-column> -->
                <el-table-column align="center" label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button type="text" @click="delRewardItem(scope.row.sourceId)" :disabled="!isEdit">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <template v-if="isEdit">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveReward">确 定</el-button>
          </template>
          <el-button v-else type="primary" @click="dialogFormVisible = false">确 定</el-button>

        </div>
      </el-dialog>
    </section>
  </div>
</template>
<script>
export default {
  name: 'sign-in-rule-edit',
  props: {
    activitySignInId: { default: '' },
    id: { default: '' }
  },
  data(){

    return{
      isEdit: this.$route.name !== 'signInView',
      dateData: {},
      formData: {
        activitySignInId: this.activitySignInId,
        activityTimeRange: [],
        activitySignInRuleRewardMapList: []
      },
      btnLoading: false,
      listLoading: false,

      rewardData: {
        signInDay: '',
        conditionType: 0,
        useCycleIndex: 0,
        rewardType: 2,
        activitySignInRewardList: []
      },
      dialogFormVisible: false,
    }
  },
  created(){
    let detailData = sessionStorage.getItem('signinData')
    this.fetchDateData()
    if (this.id !== '') {
      this.fetchData()
    } else if (detailData && !this.id) {
      const signInCopyData = JSON.parse(detailData)
      this.formData.activitySignInRuleRewardMapList = []
      signInCopyData.activitySignInRuleRewardMapList.map(i => {
        const item = {
          "signInDay": i.signInDay,
          "conditionType": i.conditionType,
          "useCycleIndex": i.useCycleIndex,
          "rewardType": i.rewardType,
          "nnum": i.nnum,
          "activitySignInRewardList":[]
        }
        i.activitySignInRewardList.map(subItem => {
          item.activitySignInRewardList.push({
            "sourceId": subItem.sourceId,
            "name": subItem.name,
            "ext1": subItem.ext1,
            "ext2": subItem.ext2,
            "ext3": subItem.ext3,
            "rewardType": subItem.rewardType
          })
        })
        this.formData.activitySignInRuleRewardMapList.push(item)
      })
    }
  },
  methods: {
    fetchData(){
      this.listLoading = true
      this.request({
        url: "/sign-in/rule/detail",
        method: "post",
        data: {
          activitySignInId: this.activitySignInId,
          id: this.id
        }
      }).then(({ data }) => {
          this.formData = {
            ...data,
            activityTimeRange: [data.startDate || '', data.endDate || '']
          }
          this.listLoading = false
        })
        .catch(err => {
          console.log(err);
          this.listLoading = false
        });
    },
    fetchDateData(){
      this.request({
        url: "/sign-in/rule/queryDate",
        method: "post",
        data: {
          activitySignInId: this.activitySignInId
        }
      }).then(({ data }) => {
          this.dateData = data
        })
        .catch(err => {
          console.log(err);
        });
    },
    showAdd(){
      this.rewardData = {
        signInDay: '',
        conditionType: 0,
        useCycleIndex: 0,
        rewardType: 2,
        activitySignInRewardList: []
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
      })
    },
    showEdit(item, index){
      this.rewardData = Object.assign({}, item, {index})
      this.dialogFormVisible = true
    },
    jumpChoose(type){
      if(type === 'coupon') {
        let checkData = this.rewardData.activitySignInRewardList.filter(item => item.rewardType === 4).map(i => {
          return {
            ...i,
            signInId: i.id,
            couponActivityId: i.sourceId,
            price: i.ext1,
            useStandard: i.ext2,
            standardPrice: i.ext3
          }
        })
        this.couponChoose({ validFlag: true }, checkData).then(val => {
          this.rewardData.activitySignInRewardList = this.rewardData.activitySignInRewardList.filter(item => item.rewardType !== 4)
          val.map(i => {
            this.rewardData.activitySignInRewardList.push(i.signInId ? { ...i, id: i.signInId } :{
              sourceId: i.couponActivityId,
              name: i.name,
              ext1: i.price,
              ext2: i.useStandard,
              ext3: i.standardPrice,
              rewardType: 4
            })
          })
        });
        return false;
      } else if(type === 'goods') {
        let checkData = this.rewardData.activitySignInRewardList.filter(item => item.rewardType === 2 && parseInt(item.goodsType)===1).map(i => {
          return {
            ...i,
            id: '',
            signInId: i.id,
            goodsId: i.sourceId
          }
        })
        this.goodsChoose({}, checkData).then(val => {
          this.rewardData.activitySignInRewardList = this.rewardData.activitySignInRewardList.filter(item => !(item.rewardType === 2 && parseInt(item.goodsType)===1))
          val.map(i => {
            this.rewardData.activitySignInRewardList.push(i.signInId ? { ...i, id: i.signInId } : {
              sourceId: i.goodsId,
              name: i.name,
              freight: i.freight || 0,
              validDays: i.validDays || 7,
              rewardType: 2,
              goodsType: 1
            })
          })
        });
      } else {
        let checkData = this.rewardData.activitySignInRewardList.filter(item => item.rewardType === 2 && parseInt(item.goodsType)===2).map(i => {
          return {
            ...i,
            signInId: i.id,
            packageId: i.sourceId,
            type: i.packType
          }
        })
        this.packageChoose({}, checkData).then(val => {
          this.rewardData.activitySignInRewardList = this.rewardData.activitySignInRewardList.filter(item => !(item.rewardType === 2 && parseInt(item.goodsType)===2))
          val.map(i => {
            this.rewardData.activitySignInRewardList.push(i.signInId ? { ...i, id: i.signInId, packType: parseInt(i.type) } : {
              sourceId: i.packageId,
              name: i.name,
              freight: i.freight || 0,
              validDays: i.validDays || 7,
              rewardType: 2,
              goodsType: 2,
              packType: parseInt(i.type)
            })
          })
        });
      }
    },
    delItem(index){
      this.formData.activitySignInRuleRewardMapList.splice(index, 1)
    },
    delRewardItem(sourceId){
      this.rewardData.activitySignInRewardList = this.rewardData.activitySignInRewardList.filter(i => i.sourceId!== sourceId)
    },
    saveReward(){
      this.$refs.dialogForm.validate(valid => {
        if(!valid){
          return;
        }

        if(!this.rewardData.activitySignInRewardList.length){
          this.$message.warning('请至少选择一种奖品')
          return;
        }
        if(this.rewardData.activitySignInRewardList.length < this.rewardData.nnum){
          this.$message.warning('最大可选数不可超过赠品数')
          return;
        }
        if(this.rewardData.index > -1){
          this.$set(this.formData.activitySignInRuleRewardMapList, this.rewardData.index, this.rewardData)
        } else {
          this.formData.activitySignInRuleRewardMapList.push(this.rewardData)
        }
        this.dialogFormVisible = false
      })

    },
    save(){
      this.$refs.form.validate(valid => {
        if(!valid){
          return;
        }

        this.btnLoading = true
        this.formData.startDate = this.formData.activityTimeRange[0]
        this.formData.endDate = this.formData.activityTimeRange[1]
        this.request({
          url: "/sign-in/rule/save",
          method: "post",
          data: this.formData
        })
          .then(() => {
            this.$router.push({ name: 'signIn' })
            this.btnLoading = false;
          })
          .catch(err => {
            console.log(err);
            this.btnLoading = false;
          });
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.sign-in-rule-edit{
  .form-static{
    span{
      color: #999;
    }
  }
  .footer-btn{
    text-align: center;
    padding: 18px;
  }
}

</style>
